<template>
  <div>
    <!-- <el-input v-model="keywords" placeholder="输入关键字查询" @input="onChange" style="margin-bottom: 5px;"/> -->
    <el-input
      class="mb20"
      clearable
      @input="handleInput"
      v-if="showSearch"
      v-model="deptName"
      placeholder="输入部门名称搜索"
    />
    <x-tree
      ref="xTree"
      :defaultExpandAll="true"
      :checkable="checkable"
      :treeData="treeData"
      @treeCheck="handleTreeCheck"
      @changeTree="handleChangeTree"
    />
  </div>
</template>

<script>
import XTree from '@/components/XTree'
import { getDeptTree } from '@/api/department'

export default {
  components: {
    XTree
  },
  props: {
    checkable: {
      type: Boolean,
      default: false
    },
    showSearch: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      keywords: '',
      list: [],
      treeData: [],
      saveTreeData: [],
      deptName: null
    }
  },
  mounted() {
    this.getDeptTree()
  },
  methods: {
    // 外层调用刷新数据方法
    refresh() {
      this.getDeptTree()
    },
    // input 搜索过滤事件
    handleInput(e) {
      let arr = []
      if (e) {
        arr = this.treeData[0].children.filter(v => v.title.indexOf(e) != -1)
      } else {
        arr = [...this.saveTreeData]
      }

      this.treeData = [
        {
          title: '部门',
          key: '',
          value: '',
          children: arr
        }
      ]
    },
    // 调用该组件时，多选的情况下，传递过来的回显值
    getKeys(arr) {
      this.$refs.xTree.getKeys(arr)
    },
    handleTreeCheck(arr) {
      this.$emit('treeCheck', arr)
    },
    getDeptTree() {
      getDeptTree().then(res => {
        let arr = [
          {
            title: '部门',
            key: '',
            value: '',
            children: res.data
          }
        ]
        this.list = arr
        this.saveTreeData = [...res.data]
        this.filterTreeData('', this.list)
      })
    },
    onChange(e) {
      const value = e
      this.filterTreeData(value, this.list)
    },
    filterTreeData(value, list) {
      // const expandedKeys = this.list.children.map(item => {
      //   console.log(item, value)
      //   if (item.title.indexOf(value) > -1) {
      //     return getParentKey(item.key, this.list.children)
      //   }
      //   return null
      // }).filter((item, i, self) => item && self.indexOf(item) === i)
      // value = value.toUpperCase()
      // list.filter(item => {
      //   const result = item.title.toUpperCase().indexOf(value) > -1
      //   this.filterTreeData(value, item.children)
      //   return result
      // })
      this.treeData = this.list
    },
    handleChangeTree(obj) {
      this.$emit('changeTree', obj)
    },
    handleCheck(checkedKeys, info) {
      this.$emit('handleCheck', checkedKeys)
    }
  }
}
</script>